//
//  HESettingViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/11.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HESettingViewController.h"
#import "HEPublicCell.h"
#import "HESettingSwitchCell.h"
#import "HESettingLogoutCell.h"
#import "HEPublicDetailCell.h"
#import "KNActionSheet.h"
#import "HEAddressViewController.h"
#import "IMSetFontSizeViewController.h"
#import "HESecurityViewController.h"

@interface HESettingViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray *sections;

@property (nonatomic, strong) GDFormModel *formModel;
@end

@implementation HESettingViewController

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"设置";
    [self.view addSubview:self.tableView];
    
    [self getCacheData];
    [self initCell];
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStyleGrouped];
        _tableView.separatorColor = CSplitLineColor;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = CViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (void)initCell {
    // 总段
    _sections = [NSMutableArray array];

    NSMutableArray *classArr = [NSMutableArray array];

    // 普通cell
    GDFiterCellModel *publicModel = [GDFiterCellModel new];
    publicModel.cellKlass = HEPublicCell.class;
    publicModel.cellType = GDFiterCellTypeSettingPublic;
 
    // switchcell
    GDFiterCellModel *switchModel = [GDFiterCellModel new];
    switchModel.cellKlass = HESettingSwitchCell.class;
    switchModel.cellType = GDFiterCellTypeSettingSwitch;
    
    // logout
    GDFiterCellModel *logoutModel = [GDFiterCellModel new];
    logoutModel.cellKlass = HESettingLogoutCell.class;
    logoutModel.cellType = GDFiterCellTypeSettingLogout;
    
    // cache
    GDFiterCellModel *cacheModel = [GDFiterCellModel new];
    cacheModel.cellKlass = HEPublicDetailCell.class;
    cacheModel.cellType = GDFiterCellTypeSettingCache;
    cacheModel.leftTitle = @"缓存清理";

    
    
    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[publicModel, switchModel, logoutModel, cacheModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];
    
    
    //
//    NSMutableArray *row1 = [NSMutableArray array];
//    GDFiterCellModel *addresModel = [GDFiterCellModel new];
//    addresModel.cellKlass = HEPublicCell.class;
//    addresModel.cellType = GDFiterCellTypeSettingAddres;
//    addresModel.leftTitle = @"地址管理";
//    [row1 addObject:addresModel];
    
    NSMutableArray *row2 = [NSMutableArray array];
    GDFiterCellModel *safeModel = [GDFiterCellModel new];
    safeModel.cellKlass = HEPublicCell.class;
    safeModel.cellType = GDFiterCellTypeSettingUsernameSafe;
    safeModel.leftTitle = @"账号与安全";
    
//    GDFiterCellModel *infoModel = [GDFiterCellModel new];
//    infoModel.cellKlass = HESettingSwitchCell.class;
//    infoModel.cellType = GDFiterCellTypeSettingInfoNotice;
//    infoModel.leftTitle = @"消息提醒";
//    infoModel.tableKey = @"st_openNotice";
    
    GDFiterCellModel *fontModel = [GDFiterCellModel new];
    fontModel.cellKlass = HEPublicCell.class;
    fontModel.cellType = GDFiterCellTypeSettingFont;
    fontModel.leftTitle = @"字体大小";
    
    
    [row2 addObject:safeModel];
//    [row2 addObject:infoModel];
    [row2 addObject:fontModel];
    [row2 addObject:cacheModel];
    
    NSMutableArray *row3 = [NSMutableArray array];
    [row3 addObject:logoutModel];
    
//    [_sections addObject:row1];
    [_sections addObject:row2];
    [_sections addObject:row3];

    [_tableView reloadData];
}

- (void)getCacheData {

    NSString *cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    // APP所占空间（MB）
    CGFloat cacheMB = [self folderSizeAtPath:cachePath];
    self.formModel.st_cache = [DYTools convertFileSize:cacheMB];
}

// 遍历文件夹获得文件夹大小，返回多少字节
- (float)folderSizeAtPath:(NSString *)folderPath {
    
    NSFileManager * manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath :folderPath]) return 0 ;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString * fileName;
    long long folderSize = 0 ;
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        if ([fileName hasPrefix:KUserCacheName]) { // 不统计用户数据
            continue;
        }
        //获取文件全路径
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize;
}

// 计算单个文件的大小
- (long long)fileSizeAtPath:(NSString *) filePath{
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath :filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

// 清空APP缓存
- (void)clearCache
{
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
    NSArray * files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    //NSLog ( @"cachpath = %@" , cachePath);
    for (NSString *p in files) {
        if ([p hasPrefix:KUserCacheName]) { // 不清理用户数据
            continue;
        }
        NSError * error = nil ;
        //获取文件全路径
        NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent :p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:fileAbsolutePath]) {
            [[NSFileManager defaultManager] removeItemAtPath:fileAbsolutePath error:&error];
        }
    }
    [Dialog toastBottom:@"清理完成"];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    
    UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    return 55;

//    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
//               [cell refreshContent:fiterModel formModel:self.formModel indexPath:indexPath];
//    }];
}

#pragma mark -

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 15)];
    v.backgroundColor = CViewBgColor;
    return v;
}

#pragma mark 解决cell分割线左侧留空的问题
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 下面这几行代码是用来设置cell的上下行线的位置
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 15, 0, 0)];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 15, 0, 0)];
    }
    
    //按照作者最后的意思还要加上下面这一段，才能做到底部线控制位置，所以这里按stackflow上的做法添加上吧。
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *rows = _sections[indexPath.section];
    GDFiterCellModel *model = rows[indexPath.row];
    
    switch (model.cellType) {
        case GDFiterCellTypeSettingCache:
        {
            [self clearCache];
            [self getCacheData];
            [self.tableView reloadData];
        }
            break;
            
        case GDFiterCellTypeSettingUsernameSafe: {
            HESecurityViewController *vc = [HESecurityViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case GDFiterCellTypeSettingFont:
        {
            IMSetFontSizeViewController *vc = [IMSetFontSizeViewController new];
            
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case GDFiterCellTypeSettingLogout:
        {
            [WOAlert alertShowTitle:@"系统提示" message:@"是否退出当前账号" cancelButtonTitle:@"取消" otherButtonTitles:@"确定" block:^(NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    [[UserManager sharedUserManager] logout:^(BOOL success, NSString *des) {
                    }];
                }
            }];
        }
            break;
        case GDFiterCellTypeSettingAddres:
        {
            HEAddressViewController *vc = [HEAddressViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
            
        default:
            break;
    }
}

@end
